package com.foreknow.hospital.service.impl;

import com.foreknow.hospital.dao.UserDao;
import com.foreknow.hospital.dao.impl.UserDaoImpl;
import com.foreknow.hospital.po.User;
import com.foreknow.hospital.service.UserService;
import com.foreknow.hospital.util.DBUtil;


import java.sql.SQLException;

public class UserServiceImpl implements UserService {

    @Override
    public User getUsersByUserIdByPass(String userId, String password) {
        User users = null;
        UserDao usersDao = new UserDaoImpl();
        try{
            users=usersDao.getUsersByUserIdByPass(userId,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close();
        }
        return users;
    }

    @Override
    public User getUsersById(User user) {
        User result ;
        UserDao usersDao = new UserDaoImpl();
        try {
            result = usersDao.getUsersById(user);
        }  catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int saveUsers(User users) {
        int result = 0;
        UserDao usersDao = new UserDaoImpl();
        try {
            //开始事务
            DBUtil.beginTransaction();
            result = usersDao.saveUsers(users);
            //提交事务
            DBUtil.commitTransaction();
        }  catch (Exception e) {
            try {
                //取消之前的所有操作
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            DBUtil.close();
        }
        return result;
    }
}
